<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Intervention\Image\ImageManagerStatic as Image;

/**
 * 身份证图片上传，然后进行ocr识别
 * Class UploadsImg
 * @package app\online_registration\controller
 */
class IdCardUploadsOcrController extends Controller
{
    /**
     * 身份证图片上传，然后进行ocr识别
     * @param card_img_front 身份证正面  允许正反面一起上传或者只上传一张
     * @param card_img_back 身份证反面
     */
    public function ocrIdCardImg(Request $request)
    {
        $file_name = array_keys($_FILES);
        if (!in_array($file_name[0], ['card_img_front', 'card_img_back']))
            return response()->json(['code' => 201, 'msg' => '上传文件名错误']);

        if (empty($_FILES['card_img_front']) && empty($_FILES['card_img_back'])) {
            return $this->returnApi(201, '请检查身份证正反面是否上传');
        }

        //验证文件类型和大小
        $file_validate = $this->fileValidate($request, $file_name[0]);
        if ($file_validate !== true) {
            return response()->json(['code' => 201, 'msg' => $file_validate]);
        }

        $card_img_front_url = '';
        if (!empty($_FILES['card_img_front'])) {
            $card_img_front = $this->uploadOneIdCard($request, $file_name[0]);
            if (empty($card_img_front)) {
                return $this->returnApi(202, '未找到资源');
            }
            // $card_img_front_url = config('other.img_addr') . $card_img_front;
            $card_img_front_url = $this->getImgAddrUrl() . $card_img_front;
            //测试使用
            //  $card_img_front_url = 'https://www.usharego.com/Uploads/card_img/2021-09-23/614c4234b1c43.jpg';
        }
        $card_img_back_url = '';
        if (!empty($_FILES['card_img_back'])) {
            $card_img_back = $this->uploadOneIdCard($request, $file_name[0]);
            if (empty($card_img_back)) {
                return $this->returnApi(202, '未找到资源');
            }
            $card_img_back_url = $this->getImgAddrUrl() . $card_img_back;
            //测试使用
            //  $card_img_back_url = 'https://www.usharego.com/Uploads/card_img/2021-09-23/614c4237af41b.jpg';
        }

        if ($card_img_front_url) {
            $card_img_front_info = $this->getIdCardBaseInfo($card_img_front_url);
            if ($card_img_front_info['code'] == 200 && $card_img_front_info['content']['errcode'] === 0 && !empty($card_img_front_info['content']['name'])) {
                $data['username'] = $card_img_front_info['content']['name'];
                $data['id_card'] = $card_img_front_info['content']['id'];
                $data['address'] = $card_img_front_info['content']['addr'];
                $data['sex'] = $card_img_front_info['content']['gender'];
                $data['nationality'] = $card_img_front_info['content']['nationality'];
                $data['birth'] = $card_img_front_info['content']['birth'];

                $data['card_img_front'] = $card_img_front;
            } else {
                Log::error('身份证人像面地址：' . $card_img_front_url);
                Log::error($card_img_front_info);
                return $this->returnApi(202, '请检查身份证人像面是否正确，请重新上传！');
            }
        }
        if ($card_img_back_url) {
            $card_img_back_info = $this->getIdCardBaseInfo($card_img_back_url);

            if ($card_img_back_info['code'] == 200 && $card_img_back_info['content']['errcode'] === 0  && !empty($card_img_back_info['content']['valid_date'])) {
                $end_time = explode('-', $card_img_back_info['content']['valid_date']);

                if (date('Ymd') > end($end_time)) {
                    return $this->returnApi(202, '此身份证已过期，不允许办证');
                }

                $data['valid_date'] = $card_img_back_info['content']['valid_date'];
                $data['authority'] = $card_img_back_info['content']['authority'];

                $data['card_img_back'] = $card_img_back;
            } else {
                Log::error('身份证国徽面地址：' . $card_img_back_url);
                Log::error($card_img_back_info);

                return $this->returnApi(202, '请检查身份证国徽面是否正确，请重新上传！');
            }
        }

        //删除过期的临时文件
        $filedir = public_path('uploads') . '/temp_img/';
        del_past_imgs($filedir, 86400); //删除过期图片

        return $this->returnApi(200,  '获取成功', true, $data);
    }

    /**
     * 单图片上传
     * @param string $img 图片name
     * @return array
     */
    public function uploadOneIdCard($request, $file_name)
    {
        //  $foldername = $file_name . 'temp_img/' . date('Y-m-d'); //$file_name.'/'.date('Y-m-d')  存放路径，按日志存储
        $file = $request->file($file_name)->store('temp_img');
        return $file;
    }

    /**
     * 文件验证
     */
    public function fileValidate($request, $file = 'file')
    {
        //获取文件真实后缀名 $request->$file->extension()
        $validator = Validator::make($request->file(), [
            $file => 'required|file|max:2048|mimes:jpg,png,jpeg',
        ], [
            //验证是否存在文件
            $file . '.required' => '文件不能为空',
            //验证是否为文件
            $file . '.file' => '请确认你的文件格式',
            //验证文件上传大小
            $file . '.max' => '文件大小不符合要求',
            //验证上传文件格式
            $file . '.mimes' => '请确认上传文件后缀',
        ]);
        if ($validator->fails()) { //如果有错误
            // return $validator->errors(); //返回得到错误
            return join('|', $validator->errors()->toArray()[$file]); //获取所有的错误，用 | 拼接
        }

        return true;
    }



    /**
     * 调用三方接口，获取身份证基本信息
     */
    public function getIdCardBaseInfo($img)
    {
        $url = 'https://www.usharego.com/readshareadmin/public/online/idCardUploadsOcr/outerIdCardBaseInfo';

        $res = request_url($url, ['img' => $img]);
        $res = json_decode($res, true);

        return $res;
    }
}
